import { createRouter, createWebHashHistory } from 'vue-router'
import { getStorage, setStorage } from '../utils/cache/storage'
import { systemManage } from './systemManage'
import Layout from '@/layouts/page/Layout.vue'
import { useInfoStore } from '@/store'
import { message } from 'ant-design-vue'
import { logManage } from './logManage'
import { taskManage } from './taskManage'
import { algManage } from './algManage'
import { videoManage } from './videoManage'
import { deviceLedgerManage } from './deviceLedgerManage'
import { resultManage } from './resultManage'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        systemManage,
        logManage,
        taskManage,
        algManage,
        videoManage,
        deviceLedgerManage,
        resultManage,
        {
          path: '',
          name: 'home',
          component: async () => await import('../views/home/index.vue')
        },
        {
          path: '404',
          name: '404',
          component: async () => await import('../views/404.vue')
        }
      ]
    },
    {
      path: '/login',
      component: async () => await import('../views/Login.vue')
    },
    {
      path: '/:catchAll(.*)',
      redirect: '/404'
    }
  ]
})

router.beforeEach(async (to, _from, next) => {
  const token = getStorage('user-token')
  if (
    to.path === '/login' ||
    to.path === '/404' ||
    (token != null && to.path === '/')
  ) {
    setStorage('last_path', to.path)
    setStorage('last_query', JSON.stringify(to.query))
    next()
    return
  }

  if (token !== null && token.length > 0) {
    const userStore = useInfoStore()
    const routers = userStore.routers
    const path = to.path
    // eslint-disable-next-line
    if (routers.includes(path) || to?.meta?.isAllowAccess) {
      setStorage('last_path', to.path)
      setStorage('last_query', JSON.stringify(to.query))
      next()
    } else {
      void message.error('您暂时无当前菜单权限，请联系管理员！')
    }
  } else {
    next('/login')
  }
})
export default router
